// 应用主逻辑
class MassageChairApp {
    constructor() {
        this.isConnected = false;
        this.currentDevice = null;
        this.statusUpdateInterval = null;
        
        this.initializeApp();
        this.setupEventListeners();
        this.setupSliderListeners();
    }

    initializeApp() {
        // 检查electronAPI是否可用
        if (!window.electronAPI) {
            console.error('Electron API 不可用');
            return;
        }

        // 检查蓝牙管理器是否可用
        if (!window.bluetoothManager) {
            console.error('蓝牙管理器不可用');
            return;
        }

        // 设置蓝牙事件监听
        window.bluetoothManager.on('connectionStateChanged', (state) => {
            this.handleConnectionStateChange(state);
        });

        window.bluetoothManager.on('dataReceived', (data) => {
            this.handleDataReceived(data);
        });

        console.log('按摩椅控制应用已初始化');
    }

    setupEventListeners() {
        // 扫描按钮
        document.getElementById('scanBtn').addEventListener('click', () => {
            this.scanForDevices();
        });

        // 断开连接按钮
        document.getElementById('disconnectBtn').addEventListener('click', () => {
            this.disconnectDevice();
        });
    }

    setupSliderListeners() {
        // 滚轮力度滑块
        const rollerSlider = document.getElementById('rollerIntensity');
        const rollerValue = document.getElementById('rollerValue');
        rollerSlider.addEventListener('input', (e) => {
            rollerValue.textContent = e.target.value;
        });

        // 气压力度滑块
        const airSlider = document.getElementById('airPressure');
        const airValue = document.getElementById('airValue');
        airSlider.addEventListener('input', (e) => {
            airValue.textContent = e.target.value;
        });

        // 4D高度滑块
        const heightSlider = document.getElementById('height4D');
        const heightValue = document.getElementById('heightValue');
        heightSlider.addEventListener('input', (e) => {
            heightValue.textContent = e.target.value;
        });

        // 屏幕亮度滑块
        const brightnessSlider = document.getElementById('brightness');
        const brightnessValue = document.getElementById('brightnessValue');
        brightnessSlider.addEventListener('input', (e) => {
            brightnessValue.textContent = e.target.value;
        });
    }

    async scanForDevices() {
        const scanBtn = document.getElementById('scanBtn');
        const deviceList = document.getElementById('deviceList');
        const devicesContainer = document.getElementById('devices');

        try {
            scanBtn.disabled = true;
            scanBtn.textContent = '扫描中...';
            
            // 显示设备列表
            deviceList.style.display = 'block';
            devicesContainer.innerHTML = '<div class="scanning">正在扫描设备...</div>';

            const devices = await window.bluetoothManager.startScanning();
            
            if (devices && devices.length > 0) {
                this.displayDevices(devices);
            } else {
                devicesContainer.innerHTML = '<div class="no-devices">未发现按摩椅设备或用户取消选择</div>';
            }
        } catch (error) {
            console.error('扫描设备时出错:', error);
            this.showError('扫描设备时出错: ' + error.message);
            devicesContainer.innerHTML = '<div class="error">扫描出错，请重试</div>';
        } finally {
            scanBtn.disabled = false;
            scanBtn.textContent = '扫描设备';
        }
    }

    displayDevices(devices) {
        const devicesContainer = document.getElementById('devices');
        
        if (devices.length === 0) {
            devicesContainer.innerHTML = '<div class="no-devices">未发现按摩椅设备</div>';
            return;
        }

        devicesContainer.innerHTML = devices.map((device, index) => `
            <div class="device-item" onclick="app.connectToDevice(${index})">
                <div class="device-info">
                    <div class="device-name">${device.name}</div>
                    <div class="device-id">${device.id}</div>
                </div>
                <div class="device-rssi">Web Bluetooth</div>
            </div>
        `).join('');
        
        // 存储设备信息供连接使用
        this.discoveredDevices = devices;
    }

    async connectToDevice(deviceIndex) {
        try {
            this.updateConnectionStatus('connecting', '连接中...');
            
            const device = this.discoveredDevices[deviceIndex];
            if (!device) {
                throw new Error('设备不存在');
            }
            
            const success = await window.bluetoothManager.connectToDevice(device);
            
            if (success) {
                this.currentDevice = device;
                this.isConnected = true;
                this.updateConnectionStatus('connected', '已连接');
                
                // 隐藏设备列表
                document.getElementById('deviceList').style.display = 'none';
                
                // 开始定期获取状态
                this.startStatusUpdates();
                
                this.showSuccess('设备连接成功');
            } else {
                this.updateConnectionStatus('disconnected', '连接失败');
                this.showError('连接失败');
            }
        } catch (error) {
            console.error('连接设备时出错:', error);
            this.updateConnectionStatus('disconnected', '连接出错');
            this.showError('连接设备时出错: ' + error.message);
        }
    }

    async disconnectDevice() {
        try {
            await window.bluetoothManager.disconnect();
            this.isConnected = false;
            this.currentDevice = null;
            this.updateConnectionStatus('disconnected', '已断开');
            this.stopStatusUpdates();
            this.showSuccess('设备已断开连接');
        } catch (error) {
            console.error('断开连接时出错:', error);
            this.showError('断开连接时出错: ' + error.message);
        }
    }

    handleConnectionStateChange(state) {
        console.log('连接状态变化:', state);
        
        if (state === 'disconnected') {
            this.isConnected = false;
            this.currentDevice = null;
            this.updateConnectionStatus('disconnected', '连接已断开');
            this.stopStatusUpdates();
        } else if (state === 'connected') {
            this.isConnected = true;
            this.updateConnectionStatus('connected', '已连接');
            this.startStatusUpdates();
        }
    }

    handleDataReceived(data) {
        console.log('接收到数据:', data);
        
        if (data.type === 'status') {
            this.updateDeviceStatus(data.data);
        } else if (data.type === 'heartRate') {
            this.updateHealthData(data.data);
        }
    }

    updateConnectionStatus(status, text) {
        const statusIndicator = document.getElementById('statusIndicator');
        const statusText = document.getElementById('statusText');
        const disconnectBtn = document.getElementById('disconnectBtn');

        statusIndicator.className = `status-indicator ${status === 'connected' ? 'online' : status === 'connecting' ? 'connecting' : 'offline'}`;
        statusText.textContent = text;
        disconnectBtn.disabled = status !== 'connected';
    }

    updateDeviceStatus(status) {
        // 更新工作模式显示
        const workModeStatus = document.getElementById('workModeStatus');
        const workModes = ['--', '舒缓', '深层', '伸展', '运动', '睡眠', '自定义'];
        workModeStatus.textContent = workModes[status.workMode] || `模式${status.workMode}`;

        // 更新时间显示
        const timeStatus = document.getElementById('timeStatus');
        timeStatus.textContent = `${String(status.timeMinute || 0).padStart(2, '0')}:${String(status.timeSecond || 0).padStart(2, '0')}`;

        // 更新滚轮力度显示
        const rollerStatus = document.getElementById('rollerStatus');
        rollerStatus.textContent = status.rollerIntensity || '--';

        // 更新气压力度显示
        const airStatus = document.getElementById('airStatus');
        airStatus.textContent = status.airPressure || '--';

        // 更新健康数据
        if (status.heartRate) {
            document.getElementById('heartRateValue').textContent = status.heartRate;
        }
        if (status.bloodOxygen) {
            document.getElementById('bloodOxygenValue').textContent = status.bloodOxygen;
        }

        // 更新加热状态
        if (status.heating) {
            document.getElementById('bodyHeat').checked = status.heating.body;
            document.getElementById('legHeat').checked = status.heating.leg;
        }
    }

    updateHealthData(healthData) {
        // 更新心率数据
        if (healthData.heartRates && healthData.heartRates.length > 0) {
            const latestHeartRate = healthData.heartRates[healthData.heartRates.length - 1];
            document.getElementById('heartRateValue').textContent = latestHeartRate || '--';
        }

        // 更新血氧数据
        if (healthData.bloodOxygens && healthData.bloodOxygens.length > 0) {
            const latestBloodOxygen = healthData.bloodOxygens[healthData.bloodOxygens.length - 1];
            document.getElementById('bloodOxygenValue').textContent = latestBloodOxygen || '--';
        }
    }

    startStatusUpdates() {
        // 每5秒获取一次设备状态 (模拟数据，实际应用中可能通过发送查询指令获取)
        this.statusUpdateInterval = setInterval(async () => {
            if (this.isConnected) {
                try {
                    // 这里可以发送状态查询指令，暂时使用模拟数据
                    const simulatedStatus = {
                        workMode: 1,
                        timeMinute: Math.floor(Math.random() * 60),
                        timeSecond: Math.floor(Math.random() * 60),
                        rollerIntensity: Math.floor(Math.random() * 3) + 1,
                        airPressure: Math.floor(Math.random() * 5) + 11,
                        heartRate: Math.floor(Math.random() * 40) + 60,
                        bloodOxygen: Math.floor(Math.random() * 10) + 95,
                        heating: {
                            body: Math.random() > 0.5,
                            leg: Math.random() > 0.5
                        }
                    };
                    this.updateDeviceStatus(simulatedStatus);
                } catch (error) {
                    console.error('获取设备状态失败:', error);
                }
            }
        }, 5000);
    }

    stopStatusUpdates() {
        if (this.statusUpdateInterval) {
            clearInterval(this.statusUpdateInterval);
            this.statusUpdateInterval = null;
        }
    }

    showSuccess(message) {
        this.showMessage(message, 'success');
    }

    showError(message) {
        this.showMessage(message, 'error');
    }

    showMessage(message, type) {
        // 创建消息提示
        const messageEl = document.createElement('div');
        messageEl.className = `message message-${type}`;
        messageEl.textContent = message;
        messageEl.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 1rem 1.5rem;
            border-radius: 8px;
            color: white;
            font-weight: 500;
            z-index: 1000;
            opacity: 0;
            transform: translateX(100px);
            transition: all 0.3s ease;
            ${type === 'success' ? 'background: linear-gradient(135deg, #27ae60, #229954);' : 'background: linear-gradient(135deg, #e74c3c, #c0392b);'}
        `;

        document.body.appendChild(messageEl);

        // 显示动画
        setTimeout(() => {
            messageEl.style.opacity = '1';
            messageEl.style.transform = 'translateX(0)';
        }, 100);

        // 自动隐藏
        setTimeout(() => {
            messageEl.style.opacity = '0';
            messageEl.style.transform = 'translateX(100px)';
            setTimeout(() => {
                document.body.removeChild(messageEl);
            }, 300);
        }, 3000);
    }
}

// 创建按摩椅控制器对象，供HTML中的事件调用
const massageChair = {
    power: async (on) => {
        try {
            const result = await window.electronAPI.protocol.createCommand('POWER', on ? 1 : 0);
            if (result.success) {
                await window.bluetoothManager.sendCommand(result.command);
                app.showSuccess(on ? '按摩椅已开机' : '按摩椅已关机');
            } else {
                app.showError('创建指令失败: ' + result.error);
            }
        } catch (error) {
            app.showError('操作失败: ' + error.message);
        }
    },

    setWorkMode: async (mode) => {
        try {
            const result = await window.electronAPI.protocol.createCommand('WORK_MODE', mode);
            if (result.success) {
                await window.bluetoothManager.sendCommand(result.command);
                const modes = ['', '舒缓', '深层', '伸展', '运动', '睡眠', '自定义'];
                app.showSuccess(`已切换到${modes[mode] || '模式' + mode}`);
            } else {
                app.showError('创建指令失败: ' + result.error);
            }
        } catch (error) {
            app.showError('设置工作模式失败: ' + error.message);
        }
    },

    setMassageTechnique: async (technique) => {
        try {
            const result = await window.electronAPI.protocol.createCommand('MASSAGE_TECHNIQUE', technique);
            if (result.success) {
                await window.bluetoothManager.sendCommand(result.command);
                const techniques = ['', '揉捏', '敲打', '指压', '滚动', '震动'];
                app.showSuccess(`已设置按摩手法: ${techniques[technique] || '手法' + technique}`);
            } else {
                app.showError('创建指令失败: ' + result.error);
            }
        } catch (error) {
            app.showError('设置按摩手法失败: ' + error.message);
        }
    },

    setRollerIntensity: async (intensity) => {
        try {
            const result = await window.electronAPI.protocol.createCommand('ROLLER_INTENSITY', parseInt(intensity));
            if (result.success) {
                await window.bluetoothManager.sendCommand(result.command);
                app.showSuccess(`滚轮力度已设置为: ${intensity}`);
            } else {
                app.showError('创建指令失败: ' + result.error);
            }
        } catch (error) {
            app.showError('设置滚轮力度失败: ' + error.message);
        }
    },

    setAirPressure: async (pressure) => {
        try {
            const result = await window.electronAPI.protocol.createCommand('AIR_PRESSURE', parseInt(pressure));
            if (result.success) {
                await window.bluetoothManager.sendCommand(result.command);
                app.showSuccess(`气压力度已设置为: ${pressure}`);
            } else {
                app.showError('创建指令失败: ' + result.error);
            }
        } catch (error) {
            app.showError('设置气压力度失败: ' + error.message);
        }
    },

    setHeight4D: async (height) => {
        try {
            const result = await window.electronAPI.protocol.createCommand('HEIGHT_4D', parseInt(height));
            if (result.success) {
                await window.bluetoothManager.sendCommand(result.command);
                app.showSuccess(`4D高度已设置为: ${height}`);
            } else {
                app.showError('创建指令失败: ' + result.error);
            }
        } catch (error) {
            app.showError('设置4D高度失败: ' + error.message);
        }
    },

    setZeroGravity: async (level) => {
        try {
            const result = await window.electronAPI.protocol.createCommand('ZERO_GRAVITY', level);
            if (result.success) {
                await window.bluetoothManager.sendCommand(result.command);
                app.showSuccess(`零重力模式已设置为: 级别${level}`);
            } else {
                app.showError('创建指令失败: ' + result.error);
            }
        } catch (error) {
            app.showError('设置零重力失败: ' + error.message);
        }
    },

    setHeating: async (body, leg) => {
        try {
            const messages = [];
            if (body !== undefined) {
                const result = await window.electronAPI.protocol.createCommand('HEAT_BODY', body ? 1 : 0);
                if (result.success) {
                    await window.bluetoothManager.sendCommand(result.command);
                    messages.push(`身体加热${body ? '开启' : '关闭'}`);
                }
            }
            if (leg !== undefined) {
                const result = await window.electronAPI.protocol.createCommand('HEAT_LEG', leg ? 1 : 0);
                if (result.success) {
                    await window.bluetoothManager.sendCommand(result.command);
                    messages.push(`腿部加热${leg ? '开启' : '关闭'}`);
                }
            }
            if (messages.length > 0) {
                app.showSuccess(messages.join(', '));
            }
        } catch (error) {
            app.showError('设置加热功能失败: ' + error.message);
        }
    },

    pause: async () => {
        try {
            const result = await window.electronAPI.protocol.createCommand('PAUSE', 1);
            if (result.success) {
                await window.bluetoothManager.sendCommand(result.command);
                app.showSuccess('已暂停按摩');
            } else {
                app.showError('创建指令失败: ' + result.error);
            }
        } catch (error) {
            app.showError('暂停失败: ' + error.message);
        }
    },

    sendCommand: async (commandType, value) => {
        try {
            const result = await window.electronAPI.protocol.createCommand(commandType, value);
            if (result.success) {
                await window.bluetoothManager.sendCommand(result.command);
                app.showSuccess('指令发送成功');
            } else {
                app.showError('创建指令失败: ' + result.error);
            }
        } catch (error) {
            app.showError('指令发送失败: ' + error.message);
        }
    },

    heartRate: async (action) => {
        try {
            const result = await window.electronAPI.protocol.createHeartRateCommand(action);
            if (result.success) {
                await window.bluetoothManager.sendCommand(result.command);
                const actions = {
                    detect: '开始心率检测',
                    save: '数据保存成功',
                    clearHeart: '心率数据已清空',
                    clearOxygen: '血氧数据已清空',
                    clearCirculation: '微循环数据已清空'
                };
                app.showSuccess(actions[action] || '操作完成');
            } else {
                app.showError('创建心率指令失败: ' + result.error);
            }
        } catch (error) {
            app.showError('心率操作失败: ' + error.message);
        }
    },

    setScreenBrightness: async (brightness) => {
        try {
            const result = await window.electronAPI.protocol.createCommand('SCREEN_BRIGHTNESS', parseInt(brightness));
            if (result.success) {
                await window.bluetoothManager.sendCommand(result.command);
                app.showSuccess(`屏幕亮度已设置为: ${brightness}`);
            } else {
                app.showError('创建指令失败: ' + result.error);
            }
        } catch (error) {
            app.showError('设置屏幕亮度失败: ' + error.message);
        }
    },

    setMassageTime: async (minutes) => {
        try {
            const result = await window.electronAPI.protocol.createCommand('MASSAGE_TIME', minutes);
            if (result.success) {
                await window.bluetoothManager.sendCommand(result.command);
                app.showSuccess(`按摩时间已设置为: ${minutes}分钟`);
            } else {
                app.showError('创建指令失败: ' + result.error);
            }
        } catch (error) {
            app.showError('设置按摩时间失败: ' + error.message);
        }
    }
};

// 初始化应用
let app;
document.addEventListener('DOMContentLoaded', () => {
    app = new MassageChairApp();
});